package core.schedule.snake.data;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import core.schedule.snake.data.domain.DsfaTask;
import core.schedule.snake.data.mydao.BaseDAO;
import core.schedule.snake.data.mydao.Datasource;
import core.schedule.snake.data.mydao.RowMapper;
import core.tool.common.DateHelper;
import core.tool.log.log4j.EasyLogger;

public class TaskService extends BaseDAO{
	
	
	public TaskService(Datasource datasource) {
		setDatasource(datasource);
	}
	
	public TaskService() {
		
	}
	
	public String updateTask(DsfaTask dafaTask) {
		EasyLogger.debug("更新任务：");
		Object[] objects=new Object[5];
		objects[0]=dafaTask.getTaskStatus();
		objects[1]=DateHelper.getFormatDate(dafaTask.getStartTime(),"yyyy-MM-dd HH:mm:ss");
		objects[2]=DateHelper.getFormatDate(dafaTask.getEndTime(),"yyyy-MM-dd HH:mm:ss");;
		objects[3]=dafaTask.getTaskResult();
		objects[4]=dafaTask.getId();
		String sql="UPDATE DSFA_SERVER_TASK D SET D.TASK_STATUS=?, D.START_TIME= to_date(?,'yyyy-mm-dd hh24:mi:ss') ,D.END_TIME=to_date(?,'yyyy-mm-dd hh24:mi:ss'),D.task_result=? WHERE D.ID=?";
		EasyLogger.debug("SQL："+sql);
		update(sql, objects);
		return "";
	}
	
	
	
	
	public List<DsfaTask> getDsfaTaskList() {
		List<DsfaTask> dsfaTaskList=new ArrayList<DsfaTask>();
//		DSFLogger.debug("数据源：");
//		DSFLogger.debug(getDatasource().toString());
		String sql="SELECT * FROM DSFA_SERVER_TASK S WHERE S.TASK_STATUS = 0 AND " +
				"((TIMMER_TYPE = 1 AND S.PLAN_STARTTIME < SYSDATE) OR TIMMER_TYPE = 2) " +
				"ORDER BY START_TIME ASC";
		EasyLogger.debug("SQL："+sql);
		dsfaTaskList=query(sql, new DsfaTaskRowerMapper());
//		DSFLogger.debug("结果集数量："+dsfaTaskList.size());
		return dsfaTaskList;
	}
	
	
	class DsfaTaskRowerMapper implements RowMapper {
		public Object map(ResultSet rs) throws SQLException {
			DsfaTask dsfaTask=new DsfaTask();
			dsfaTask.setTaskName(rs.getString("task_name"));
			dsfaTask.setTaskType(rs.getString("task_type"));
			dsfaTask.setTaskStatus(rs.getString("task_status"));
			dsfaTask.setTaskResult(rs.getString("task_result"));
			dsfaTask.setCreateId(rs.getString("createid"));
			dsfaTask.setCreteTime(rs.getDate("createtime"));
			dsfaTask.setPlanStartTime(rs.getDate("plan_starttime"));
			dsfaTask.setStartTime(rs.getDate("start_time"));
			dsfaTask.setEndTime(rs.getDate("end_time"));
			dsfaTask.setId(rs.getString("id"));
			dsfaTask.setTaskRule(rs.getString("TASK_RULE"));
			dsfaTask.setTimmerType(rs.getInt("TIMMER_TYPE"));
			dsfaTask.setExectStr(rs.getString("EXECT_STR"));
			return dsfaTask;
		}
	}

	

}
